package _58_对称的二叉树;

import java.util.LinkedList;

class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}

/*
题目描述
请实现一个函数，用来判断一颗二叉树是不是对称的。注意，如果一个二叉树同此二叉树的镜像是同样的，定义其为对称的。
 */
public class Solution {
    boolean isSymmetrical(TreeNode pRoot) {
        if (pRoot == null) return true;
        LinkedList<TreeNode> q = new LinkedList();
        q.offerLast(pRoot);
        while (!q.isEmpty()) {
            int size = q.size();
            int start = 0;
            int end = size - 1;

            while (start < end) {
                TreeNode left = q.get(start++);
                TreeNode right = q.get(end--);
                if (left == null || right == null) {
                    if (left == null && right == null) {
                        continue;
                    } else {
                        return false;
                    }
                } else if (left.val != right.val) {
                    return false;
                }
            }
            for (int i = 0; i < size; i++) {
                TreeNode root = q.pollFirst();
                if (root == null) continue;
                q.offerLast(root.left);
                q.offerLast(root.right);
            }
        }
        return true;
    }

    boolean isSymmetrical2(TreeNode pRoot) {
        if (pRoot == null) return true;
        return digui(pRoot.left, pRoot.right);
    }

    boolean digui(TreeNode left, TreeNode right) {
        if (left == null) return right == null;
        if (right == null) return false;
        if (right.val != left.val) return false;
        return digui(left.left, right.right) && digui(left.right, right.left);
    }
}
